package com.hsgene.order.service.impl;

import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.dict.dto.SysDictDto;
import com.hsgene.generator.constants.GeneratorEnum;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.order.condition.AgencyOrderCondition;
import com.hsgene.order.constants.v1.*;
import com.hsgene.order.domain.OrderPackage;
import com.hsgene.order.domain.OrderPackageDetail;
import com.hsgene.order.domain.SendReport;
import com.hsgene.order.domain.v1.GeneticOrderOperationDetail;
import com.hsgene.order.domain.v1.GeneticTestingOrderAddtionA;
import com.hsgene.order.domain.v1.GeneticTestingOrderPackageSend;
import com.hsgene.order.dto.agency.*;
import com.hsgene.order.dto.console.ConsoleOrderInterchangeDto;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.persistence.*;
import com.hsgene.order.service.AgencyOrderService;
import com.hsgene.order.service.OrderPostponeService;
import com.hsgene.order.service.OrderService;
import com.hsgene.order.service.api.DictService;
import com.hsgene.order.service.api.GeneratorService;
import com.hsgene.order.service.api.SampleService;
import com.hsgene.sample.constants.TypeLabel;
import com.hsgene.sample.dto.GeneticTestingSampleDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.apache.coyote.http11.Constants.a;

/**
 * @desc: 机构订单serviceImpl
 * @author: 江承良
 * @date: 2018/9/20 11:54
 */
@Service
public class AgencyOrderServiceImpl implements AgencyOrderService {
    private Logger logger = LoggerFactory.getLogger(AgencyOrderServiceImpl.class);
    @Resource
    private AgencyOrderRepository agencyOrderRepository;
    @Resource
    GeneratorService generatorService;
    @Resource
    OrderPackageDetailMapper orderPackageDetailMapper;
    @Resource
    OrderPackageMapper orderPackageMapper;
    @Resource
    private SampleService sampleService;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private GeneticTestingOrderPackageSendMapper sendMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private DictService dictService;

    @Resource
    private OrderPostponeService orderPostponeService;

    /**
     * 机构订单列表
     *
     * @param condition              机构订单查询条件
     * @param geneticTestingAgencyId 检测机构id
     * @param limitHelper            分页条件
     * @return
     */
    @Override
    public ApiResult<Pagination<AgencyOrderDto>> queryAgencyOrders(AgencyOrderCondition condition, String
            geneticTestingAgencyId, LimitHelper limitHelper) {
        FieldChecker.checkEmpty(limitHelper, "分页参数");
        //此处需要将前端传的订单状态改为订单套餐状态
        if(condition.getOrderStatus()!=null){
            if(OrderStatus.WAIT_SAMPLE_CONFIRM.getCode()==condition.getOrderStatus()){
                condition.setOrderStatus(1);
            }else if(OrderStatus.TESTING.getCode()==condition.getOrderStatus()){
                condition.setOrderStatus(2);
            }
        }
        int count = agencyOrderRepository.queryAgencyOrderCount(condition, geneticTestingAgencyId);
        Pagination<AgencyOrderDto> pagination = Pagination.newInstance(limitHelper, count);
        List<AgencyOrderDto> agencyOrderDtos = new ArrayList<>();
        if (count > 0) {
            agencyOrderDtos = agencyOrderRepository.queryAgencyOrders(condition, geneticTestingAgencyId, limitHelper);
            if (agencyOrderDtos != null && agencyOrderDtos.size() > 0) {
                int rowNum = (limitHelper.getPage() - 1) * limitHelper.getSize();
                for (int i = 0; i < agencyOrderDtos.size(); i++) {
                    AgencyOrderDto agencyOrderDto = agencyOrderDtos.get(i);
                    //根据对应的状态码转换性别及状态
                    if (agencyOrderDto != null) {
                        if (agencyOrderDto.getPatientSex() != null) {
                            agencyOrderDto.setPatientSexDesc(SexType.sex(agencyOrderDto.getPatientSex()));
                        }
                        agencyOrderDto.setStatusDesc(OrderPackageStatus.desc(agencyOrderDto.getStatus()));
                        String requisitionNo = agencyOrderRepository.queryRequisition(agencyOrderDto
                                .getGeneticTestingAgencyId(), agencyOrderDto.getGeneticTestingOrderId());
                        agencyOrderDto.setRequisitionNo(requisitionNo);
                        //处理序号
                        agencyOrderDto.setNumber(rowNum + i + 1);
                    }
                }
            }
        }
        pagination.setResult(agencyOrderDtos);
        return new ApiResult<>(200, "success", "机构订单列表查询成功", pagination);
    }

    /**
     * 机构订单管理——申请单查询
     *
     * @param geneticTestingOrderId 订单id
     * @return
     */
    @Override
    public ApiResult queryAgencyOrderRequisition(String geneticTestingOrderId) {
        PatientInfoDto patientInfoDto = agencyOrderRepository.queryPatientInfoDto(geneticTestingOrderId);
        patientInfoDto.setPatientSexDesc(SexType.sex(patientInfoDto.getPatientSex()));
        if (patientInfoDto.getIsBeforeDoneGeneticTesting() != null) {
            String desc = patientInfoDto.getIsBeforeDoneGeneticTesting() == 1 ? "是" : "否";
            patientInfoDto.setIsBeforeDoneGeneticTestingDesc(desc);
        }
        //申请单不需要展示的套餐
        List<String> excludePackageIds = checkOrderChangePackage(geneticTestingOrderId);
        excludePackageIds = excludePackageIds==null||excludePackageIds.size()==0?null:excludePackageIds;
        //查询申请单信息
        List<AgencyOrderRequisitionDto> orderRequisitionDtos = agencyOrderRepository.queryAgencyOrderRequisition
                (geneticTestingOrderId,excludePackageIds);
        orderRequisitionDtos.forEach(agencyOrderRequisitionDto -> {
            if (agencyOrderRequisitionDto != null) {
                String requisitionNo = agencyOrderRepository.queryRequisition(agencyOrderRequisitionDto
                        .getGeneticTestingAgencyId(), geneticTestingOrderId);
                agencyOrderRequisitionDto.setRequisitionNo(requisitionNo);
                //处理申请单样本信息
                if (!StringUtils.isEmpty(agencyOrderRequisitionDto.getSampleIds())) {
                    String[] sampleIds = agencyOrderRequisitionDto.getSampleIds().split(",");
                    List<SampleInfoDto> sampleInfoDtos = new ArrayList<>();
                    if (sampleIds != null && sampleIds.length > 0) {
                        for (int i = 0; i < sampleIds.length; i++) {
                            SampleInfoDto sampleInfoDto = new SampleInfoDto();
                            sampleInfoDto.setSampleBarcode(agencyOrderRequisitionDto.getSampleBarcode());
                            //查询样本信息
                            ApiResult<GeneticTestingSampleDto> sampleDtoApiResult = sampleService.queryById
                                    (sampleIds[i], TypeLabel.LABEL.getDesc());
                            if (sampleDtoApiResult.isSucc()) {
                                if (sampleDtoApiResult.getData() != null) {
                                    sampleInfoDto.setSmapleType(sampleDtoApiResult.getData().getLabel());
                                    //判断样本是否需要切片数量
                                    if (!StringUtils.isEmpty(sampleDtoApiResult.getData().getParentLabelKey()) &&
                                        sampleDtoApiResult.getData().getParentLabelKey().contains("1")) {
                                        sampleInfoDto.setWhiteCount(agencyOrderRequisitionDto.getWhiteCount());
                                    }
                                    //判断样本是否需要医院编码
                                    if (!StringUtils.isEmpty(sampleDtoApiResult.getData().getParentLabelKey()) &&
                                        sampleDtoApiResult.getData().getParentLabelKey().contains("2")) {
                                        sampleInfoDto.setHospitalCode(agencyOrderRequisitionDto.getHospitalCode());
                                    }
                                } else {
                                    logger.error("机构确认样本弹窗信息没有查询到对应的样本信息");
                                }
                            } else {
                                logger.error("机构确认样本弹窗信息查询到对应的样本信息出错");
                            }
                            sampleInfoDtos.add(sampleInfoDto);
                        }
                    }
                    agencyOrderRequisitionDto.setSampleInfoDtos(sampleInfoDtos);
                }
            }
        });
        RequisitionInfoDto requisitionInfoDto = new RequisitionInfoDto();
        requisitionInfoDto.setPatientInfoDto(patientInfoDto);
        requisitionInfoDto.setAgencyOrderRequisitionDtos(orderRequisitionDtos);
        return new ApiResult(200, "success", "申请单获取成功", requisitionInfoDto);
    }

    /***
     * 检查订单是否变更过套餐，如果变更过需要根据不同情况查询申请单内容
     * 确认变更前，申请单保持不变；
     * 确认变更后，不需要补款的，原申请单作废，生成新申请单；
     * 确认变更后，需要补款但未补款的，申请单保持不变；
     * 确认变更后，需要补款的且已经补款的，原申请单作废，生成新申请单
     * @author jcl
     * @date 2019/1/29 13:47
     * @param orderId 订单id
     * @return
     */
    private List<String> checkOrderChangePackage(String orderId){
        GeneticTestingOrderAddtionA addtionA = orderRepository.findAddtionAByOrderId(orderId);
        List<ConsoleOrderInterchangeDto> orderInterchangeDtos = orderRepository.consoleOrderInterchanges(orderId);
        List<String> packageIds = new ArrayList<>();
        //如果此套餐未变更，则申请单内容不变
        if(addtionA.getPackageChangeFlag()==null){
            return packageIds;
        }else if(addtionA.getPackageChangeFlag()==0){
            //如果套餐变更未确认，申请单保持不变
            orderInterchangeDtos.forEach(consoleOrderInterchangeDto -> {
                packageIds.add(consoleOrderInterchangeDto.getNewPackageId());
            });
        }else {
            //确认变更后
            orderInterchangeDtos.forEach(consoleOrderInterchangeDto -> {
                //不需要补款
                if(consoleOrderInterchangeDto.getReplenishmentFlag()!=1){
                    packageIds.add(consoleOrderInterchangeDto.getOldPackageId());
                }else {
                    //需要补款
                    if(consoleOrderInterchangeDto.getStatus()!=2){
                        //未补款
                        packageIds.add(consoleOrderInterchangeDto.getNewPackageId());
                    }else {
                        //补款完成
                        packageIds.add(consoleOrderInterchangeDto.getOldPackageId());
                    }
                }
            });
        }
        return packageIds;
    }

    /**
     * @param
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @description 获取所有检测机构
     * @author maodi
     * @createDate 2018/11/1 17:17
     */
    @Override
    public List<Map<String, Object>> agencies() {
        return agencyOrderRepository.agencies();
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public ApiResult uploadReport(OrderPackageDetail orderPackageDetail) {

        if (org.apache.commons.lang.StringUtils.isEmpty(orderPackageDetail.getReportUrl())) {
            return ApiResult.fail(OrderErrorCode.TEST_REPORT_CANNOT_BE_EMPTY);
        }
        //判断a表package_change_flag是未确认，不能上传
        GeneticTestingOrderAddtionA addtionAByOrderId = orderRepository.findAddtionAByOrderId(orderPackageDetail.getGeneticTestingOrderId());
        if(addtionAByOrderId.getPackageChangeFlag()!=null&&addtionAByOrderId.getPackageChangeFlag()==0){
          return ApiResult.fail(OrderErrorCode.CHANGE_PACKAGE_NOT_CONFIRMED);
        }
        //第一次上传就添加，如果是审核未通过再上传，就更新
        OrderPackageDetail detail = orderPackageDetailMapper.getDetailByOrderIdAndPackageId(orderPackageDetail);
        orderPackageDetail.setReportUploadDateTime(new Date());
        orderPackageDetail.setReportUploadFlag(ReportUploadFlag.getEnum(orderPackageDetail.getReportUploadFlag())
                .getCode());
        orderPackageDetail.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        if (detail == null) {
            ApiResult<GeneratorDto> generator = generatorService.getGenerator(null, null);
            if (!generator.isSucc()) {
                return ApiResult.fail(generator.getError());
            }
            ApiResult<GeneratorDto> generatorDtoApiResult = generatorService.numberGenerator(GeneratorEnum.GTRN
                    .getType(), null, null);
            if (!generatorDtoApiResult.isSucc()) {
                return ApiResult.fail(generatorDtoApiResult.getError());
            }
            orderPackageDetail.setReportNo(generatorDtoApiResult.getData().getSerialNumber());
            orderPackageDetail.setId(generator.getData().getSerialNumber());
            orderPackageDetailMapper.insertSelective(orderPackageDetail);
        } else {
            orderPackageDetail.setReportNo(detail.getReportNo());
            orderPackageDetail.setId(detail.getId());
            //重新上传，审核未通过原因和状态要置为null
            orderPackageDetailMapper.updateDetailReport(orderPackageDetail);
        }
        //降orderPackage状态改为3-报告待审核
        OrderPackage orderPackage = new OrderPackage();
        orderPackage.setPackageId(orderPackageDetail.getPackageId());
        orderPackage.setGeneticTestingOrderId(orderPackageDetail.getGeneticTestingOrderId());
        orderPackage.setStatus(OrderPackageStatus.REPORT_CHECK.getCode());
        orderPackageMapper.updateByPackageIdAndOrder(orderPackage);
        // 清除订单套餐超期检测标志
        orderPostponeService.clearPostpone(orderPackage.getGeneticTestingOrderId(), orderPackage.getPackageId());
        //保存操作记录-如果是平台上传多个，保存一条记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderPackageDetail.getGeneticTestingOrderId());
        orderOperationDetail.setOperatorId(orderPackageDetail.getUploader());
        orderOperationDetail.setStatus(OrderStatus.TESTING.getCode());
        orderOperationDetail.setDescription("上传报告");
        orderOperationDetail.setOrderType(2);
        orderOperationDetail.setPackageId(orderPackageDetail.getPackageId());
        orderService.orderOperationLog(orderOperationDetail);
        return ApiResult.succ();
    }

    /**
     * 寄送报告
     *
     * @param sendReport
     * @return
     * @author FX
     * @date 2018/11/8 18:16
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public ApiResult sendAReport(SendReport sendReport, String userId) {
        //插入寄送信息
        ApiResult<GeneratorDto> generator = generatorService.getGenerator(null, null);
        if (!generator.isSucc()) {
            return ApiResult.fail(generator.getError());
        }
        GeneticTestingOrderPackageSend geneticTestingOrderPackageSend = new GeneticTestingOrderPackageSend();
        geneticTestingOrderPackageSend.setId(generator.getData().getSerialNumber());
        geneticTestingOrderPackageSend.setGeneticTestingOrderId(sendReport.getOrderId());
        geneticTestingOrderPackageSend.setCourierDateTime(new Date());
        geneticTestingOrderPackageSend.setDeleteFlag(0);
        BeanUtils.copyProperties(sendReport, geneticTestingOrderPackageSend);
        sendMapper.insertSelective(geneticTestingOrderPackageSend);

        OrderPackage orderPackage = new OrderPackage();
        orderPackage.setPackageId(sendReport.getPackageId());
        orderPackage.setGeneticTestingOrderId(sendReport.getOrderId());
        //如果套餐状态是未寄回，余钠是否已寄回改为已寄回
        //fix bug20665 如果是未寄回并且寄送物品有余钠，改为已寄回
        OrderPackage orderPackage1 = orderPackageMapper.selectByPackageIdAndOrder(orderPackage);
        if (orderPackage1.getIsSendWaxBlock() != null && orderPackage1.getIsSendWaxBlock() == 1) {
            if (sendReport.getItemsName().contains("余蜡")) {
                OrderPackage aPackage = new OrderPackage();
                aPackage.setIsSendWaxBlock(2);
                aPackage.setGeneticTestingOrderId(sendReport.getOrderId());
                aPackage.setPackageId(sendReport.getPackageId());
                orderPackageMapper.updateByPackageIdAndOrder(aPackage);
            }
        }
        //是最后一次寄送，订单套餐状态改为5-待签收
        if (sendReport.getIsLastSend() == 1) {
            orderPackage.setStatus(OrderPackageStatus.PENDING_SIGN.getCode());
            orderPackageMapper.updateByPackageIdAndOrder(orderPackage);
        }
        //如果订单套餐下的所有套餐状态都是5-代签收，订单状态改为14-代签收材料
        List<OrderPackage> packageByOrderId = orderPackageMapper.getPackageByOrderId(sendReport.getOrderId());
        boolean b = packageByOrderId.stream()
                .filter(c -> c.getStatus() != OrderPackageStatus.END.getCode())
                .allMatch(c -> c.getStatus() == OrderPackageStatus.PENDING_SIGN.getCode());
        /*boolean isSignAll = true;
        for (OrderPackage c : packageByOrderId) {
            if (c.getStatus() != null) {
                if (c.getStatus() == OrderPackageStatus.END.getCode()) {
                    continue;
                }
                if (c.getStatus() != OrderPackageStatus.PENDING_SIGN.getCode()) {
                    isSignAll = false;
                }
            }
        }*/
        if (b) {
            orderRepository.updateTestingOrderStatus(sendReport.getOrderId(), OrderStatus.MAIL.getCode(), new Date());
        }
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(sendReport.getOrderId());
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(OrderStatus.PENDING_PAYMENT.getCode());
        orderOperationDetail.setDescription("寄送物品");
        orderOperationDetail.setOrderType(2);
        orderOperationDetail.setPackageId(sendReport.getPackageId());
        orderService.orderOperationLog(orderOperationDetail);
        return ApiResult.succ();
    }

    /***
     * 机构确认样本弹窗信息展示
     * @author jcl
     * @date 2018/11/8 9:36
     * @param orderId 订单id
     * @param packageId 套餐id
     * @return
     */
    @Override
    public ApiResult<SampleConfirmDto> sampleConfirmInfo(String orderId, String packageId) {
        SampleConfirmDto sampleConfirmDto = agencyOrderRepository.sampleConfirmInfo(orderId, packageId);
        List<SampleInfoDto> sampleInfoDtos = sampleInfo(sampleConfirmDto);
        sampleConfirmDto.setSampleInfoDtos(sampleInfoDtos);
        if (!StringUtils.isEmpty(sampleConfirmDto.getCourierCompanyName())) {
            sampleConfirmDto.setCourierCompanyName(ExpressCompanyType.getEnum(sampleConfirmDto.getCourierCompanyName
                    ()).getDesc());
        }
        // return new ApiResult(200, "success", "获取数据成功", sampleConfirmDto);
        return ApiResult.succ(sampleConfirmDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> sampleConfirm(SampleConfirmDto sampleConfirmDto, String userId) {
        // 请求参数校验
        FieldChecker.checkEmpty(sampleConfirmDto, "样本确认信息");
        sampleConfirmDto.setSigner(userId);
        sampleConfirmDto.signCheck();
        // 数据对比与状态校验
        SampleConfirmDto origin = agencyOrderRepository.sampleConfirmInfo(sampleConfirmDto.getOrderId(),
                sampleConfirmDto.getPackageId());
        if (origin == null) {
            logger.error("机构签收样本失败：订单[{}]套餐[{}]不存在！", sampleConfirmDto.getOrderId(), sampleConfirmDto.getPackageId());
            return ApiResult.failFormatTip(OrderErrorCode.ORDER_SAMPLE_SIGN_EXCEPTION, "签收信息不存在");
        }
        OrderPackageStatus currentStatus = OrderPackageStatus.getEnum(origin.getStatus());
        String tip = "";
        if (OrderPackageStatus.NONE_BEGIN.equals(currentStatus)) {
            tip = "当前状态不允许进行样本确认操作！";
        } else if (!OrderPackageStatus.SAMPLE_CONFIRM.equals(currentStatus)) {
            tip = "样本已确认，请勿重复操作！";
        }
        if (!StringUtils.isEmpty(tip)) {
            return ApiResult.failFormatTip(OrderErrorCode.ORDER_SAMPLE_SIGN_EXCEPTION, tip);
        }
        //验证是否是变更过的套餐
        GeneticTestingOrderAddtionA addtionA = orderRepository.findAddtionAByOrderId(sampleConfirmDto.getOrderId());
        if(addtionA.getPackageChangeFlag()!=null){
            //变更未确认订单
            if(addtionA.getPackageChangeFlag() == 0){
                return ApiResult.fail(OrderErrorCode.ORDER_PACKAGE_CHANGE_NO_CONFIRM);
            }else {
                //变更已确认
                ConsoleOrderInterchangeDto orderInterchangeDto = orderRepository.orderInterchange(sampleConfirmDto.getOrderId(),sampleConfirmDto.getPackageId());
                if(orderInterchangeDto.getReplenishmentFlag() == 1 && orderInterchangeDto.getStatus() != 2){
                    //未补款不能确认样本
                    return ApiResult.fail(OrderErrorCode.ORDER_PACKAGE_CHANGE_NO_SUPPLEMENT);
                }
            }
        }
        // 校验通过，变更订单套餐状态，更新样本确认信息
        origin.setSignerDateTime(new Date());
        origin.setStatus(OrderPackageStatus.REPORT_UPLOAD.getCode());
        origin.setSigner(userId);
        agencyOrderRepository.sampleConfirmByDto(origin);
        // 修改状态后判断该订单中所有套餐样本是否已全部确认，若已全部确认则修改订单状态
        // fix BUG[19840] 某订单的所有套餐机构确认样本后，订单状态未更改为报告待上传
        // 更改SQL逻辑，追加状态排序，状态值越小越靠前，当前最小状态都已确认样本时，
        // 订单已全部确认样本，变更订单状态为(9:报告待上传)
        List<Integer> status = agencyOrderRepository.orderPackageStatus(sampleConfirmDto.getOrderId());
        if (!CollectionUtils.isEmpty(status)
            && !OrderPackageStatus.SAMPLE_CONFIRM.equals(OrderPackageStatus.getEnum(status.get(0)))) {
            orderRepository.updateTestingOrderStatus(sampleConfirmDto.getOrderId(), OrderStatus.TESTING.getCode(),
                    new Date());
        }
        // 发送订单超期检测消息
        orderPostponeService.orderSampleConfirmed(sampleConfirmDto.getOrderId(), sampleConfirmDto.getPackageId());
        // 记录操作日志
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(sampleConfirmDto.getOrderId());
        orderOperationDetail.setPackageId(sampleConfirmDto.getPackageId());
        orderOperationDetail.setOrderType(2);
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setDescription("确认样本");
        orderOperationDetail.setStatus(OrderStatus.WAIT_SAMPLE_CONFIRM.getCode());
        orderService.orderOperationLog(orderOperationDetail);
        return ApiResult.succ();
    }

    /***
     * 机构订单详情
     * @author jcl
     * @date 2018/11/12 10:01
     * @param orderId 订单id
     * @param packageId 套餐id
     * @return
     */
    @Override
    public ApiResult<AgencyOrderDetailDto> agencyOrderDetail(String orderId, String packageId) {
        AgencyOrderDetailDto orderDetailDto = new AgencyOrderDetailDto();
        // 基础信息查询
        AgencyOrderDetailBaseInfoDto agencyOrderBaseInfo = agencyOrderRepository.agencyOrderBaseInfo(orderId,
                packageId);
        if (agencyOrderBaseInfo != null && !StringUtils.isEmpty(agencyOrderBaseInfo.getAgencyId())) {
            String requisitionNo = agencyOrderRepository.queryRequisition(agencyOrderBaseInfo.getAgencyId(), orderId);
            agencyOrderBaseInfo.setRequisitionNo(requisitionNo);
        }
        if (agencyOrderBaseInfo != null && agencyOrderBaseInfo.getIsBeforeDoneGeneticTesting() != null) {
            String desc = agencyOrderBaseInfo.getIsBeforeDoneGeneticTesting() == 1 ? "是" : "否";
            agencyOrderBaseInfo.setIsBeforeDoneGeneticTestingDesc(desc);
        }
        // 处理机构订单流程图展示位置
        if (agencyOrderBaseInfo != null && agencyOrderBaseInfo.getStatus() != null) {
            // fix BUG[19811] 机构订单详情页，详情页中的流程节点显示不正确
            agencyOrderBaseInfo.setPosition(AgencyOrderPosition.getOrderPosition(agencyOrderBaseInfo
                    .getAgencyOrderStatus()));
        }
        orderDetailDto.setAgencyOrderDetailBaseInfo(agencyOrderBaseInfo);
        // 项目信息
        SampleConfirmDto sampleConfirmDto = agencyOrderRepository.sampleConfirmInfo(orderId, packageId);
        List<SampleInfoDto> sampleInfoDtos = sampleInfo(sampleConfirmDto);
        sampleConfirmDto.setSampleInfoDtos(sampleInfoDtos);
        //快递方式枚举处理
        sampleConfirmDto.setCourierCompanyName(ExpressCompanyType.getEnum(sampleConfirmDto.getCourierCompanyName())
                .getDesc());
        orderDetailDto.setPackageInfo(sampleConfirmDto);
        // 报告信息
        OrderPackageReportDto agencyOrderReport = agencyOrderRepository.agencyOrderReport(orderId, packageId);
        if (agencyOrderReport != null && !StringUtils.isEmpty(agencyOrderReport.getMolecular())) {
            ApiResult<SysDictDto> dtoApiResult = dictService.sysDict(agencyOrderReport.getMolecular());
            if (200 == dtoApiResult.getCode() && dtoApiResult.getData() != null) {
                agencyOrderReport.setMolecular(dtoApiResult.getData().getValue());
            }
            if (!StringUtils.isEmpty(agencyOrderReport.getReportUrl())) {
                agencyOrderReport.setReportUrl(QiniuCertificateUtil.getOneDownloadCertificate(agencyOrderReport
                        .getReportUrl()));
            }
        }
        orderDetailDto.setOrderPackageReport(agencyOrderReport);
        // 寄送信息
        List<AgencyOrderSendInfoDto> agencyOrderSendInfos = agencyOrderRepository.agencyOrderSendInfo(orderId,
                packageId);
        orderDetailDto.setAgencyOrderSendInfos(agencyOrderSendInfos);
        // 操作记录
        List<AgencyOrderOperationDto> agencyOrderOperations = agencyOrderRepository.agencyOrderOperation(orderId,
                packageId);
        if (agencyOrderOperations != null && agencyOrderOperations.size() > 0) {
            for (AgencyOrderOperationDto agencyOrderOperation : agencyOrderOperations) {
                if (agencyOrderOperation.getStatus() != null) {
                    agencyOrderOperation.setStatusDesc(OrderStatus.getEnum(agencyOrderOperation.getStatus()).getDesc());
                }
            }
        }
        orderDetailDto.setAgencyOrderOperations(agencyOrderOperations);
        //return new ApiResult(200,"success","数据获取成功",orderDetailDto);
        return ApiResult.succ(orderDetailDto);
    }

    /***
     * 处理样本信息
     * @author jcl
     * @date 2018/11/12 15:39
     * @param sampleConfirmDto
     * @return
     */
    public List<SampleInfoDto> sampleInfo(SampleConfirmDto sampleConfirmDto) {
        List<SampleInfoDto> sampleInfoDtos = new ArrayList<>();
        if (!StringUtils.isEmpty(sampleConfirmDto.getSampleIds())) {
            String[] sampleIds = sampleConfirmDto.getSampleIds().split(",");
            if (sampleIds != null && sampleIds.length > 0) {
                for (int i = 0; i < sampleIds.length; i++) {
                    SampleInfoDto sampleInfoDto = new SampleInfoDto();
                    //查询样本信息
                    ApiResult<GeneticTestingSampleDto> sampleDtoApiResult = sampleService.queryById(sampleIds[i],
                            TypeLabel.LABEL.getDesc());
                    if (sampleDtoApiResult.isSucc()) {
                        if (sampleDtoApiResult.getData() != null) {
                            sampleInfoDto.setSmapleType(sampleDtoApiResult.getData().getLabel());
                            //判断样本是否需要切片数量
                            if (!StringUtils.isEmpty(sampleDtoApiResult.getData().getParentLabelKey()) &&
                                sampleDtoApiResult.getData().getParentLabelKey().contains("1")) {
                                sampleInfoDto.setWhiteCount(sampleConfirmDto.getWhiteCount());
                            }
                            //判断样本是否需要医院编码
                            if (!StringUtils.isEmpty(sampleDtoApiResult.getData().getParentLabelKey()) &&
                                sampleDtoApiResult.getData().getParentLabelKey().contains("2")) {
                                sampleInfoDto.setHospitalCode(sampleConfirmDto.getHospitalCode());
                            }
                        } else {
                            logger.error("机构确认样本弹窗信息没有查询到对应的样本信息");
                        }
                    } else {
                        logger.error("机构确认样本弹窗信息查询到对应的样本信息出错");
                    }
                    sampleInfoDtos.add(sampleInfoDto);
                }
            }
        }
        return sampleInfoDtos;
    }
}
